﻿#region Copyright Notice
// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using AbstractClass.Linq;

namespace AbstractClass
{
    /// <summary>
    /// Represents a function pipeline.
    /// </summary>
    /// <typeparam name="T">The type of the input to the pipeline.</typeparam>
    public class Pipe<T>
    {
        private readonly List<Func<T, T>> _funcStore = new List<Func<T, T>>();
        private Func<T, T> _delegate;

        /// <summary>
        /// Initializes a new instance of the <see cref="Pipe&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="funcs">The constituents functions in the pipeline.</param>
        private Pipe(params Func<T, T>[] funcs)
        {
            _funcStore = new List<Func<T, T>>(funcs);
        }

        /// <summary>
        /// Gets the total number of constituent functions in the pipeline.
        /// </summary>
        /// <value>The number of constituent functions.</value>
        public int PipeCount
        {
            get { return _funcStore.Count; }
        }

        /// <summary>
        /// Creates a function pipeline from an unknown number of functions.
        /// </summary>
        /// <param name="funcs">The constituent functions in the pipeline.</param>
        /// <returns>A function pipeline.</returns>
        public static Pipe<T> Create(params Func<T, T>[] funcs)
        {
            return new Pipe<T>(funcs);
        }

        /// <summary>
        /// Adds a number of functions to the current pipeline.
        /// </summary>
        /// <param name="func">The a number of functions to add to this pipeline.</param>
        /// <returns></returns>
        public Pipe<T> AddPipe(params Func<T, T>[] func)
        {
            func.Process(_funcStore.Add);
            return this;
        }

        /// <summary>
        /// Executes the pipeline.
        /// </summary>
        /// <param name="arg">The argument to the pipeline.</param>
        /// <returns>The final output of the pipeline.</returns>
        public T Invoke(T arg)
        {
            T value = Execute(arg);
            return value;
        }

        /// <summary>
        /// Begins an asynchronous invocation of the pipeline.
        /// </summary>
        /// <param name="arg">The argument of the pipeline.</param>
        /// <param name="callback">The <see cref="AsyncCallback"/> delegate.</param>
        /// <param name="userState">The state object for this operation.</param>
        /// <returns>>The status of the asynchronous operation.</returns>
        public IAsyncResult BeginInvoke(T arg, AsyncCallback callback, object userState)
        {
            _delegate = Execute;
            return _delegate.BeginInvoke(arg, callback, userState);
        }

        /// <summary>
        /// Ends an asynchronous invocation of the pipeline.
        /// </summary>
        /// <param name="asyncResult">The status of this asynchronous invocation.</param>
        /// <returns>The final output of the pipeline.</returns>
        /// <exception cref="InvalidOperationException"><see cref="EndInvoke"/> is called before calling <see cref="BeginInvoke"/>.</exception>
        public T EndInvoke(IAsyncResult asyncResult)
        {
            if (_delegate != null)
            {
                T result = _delegate.EndInvoke(asyncResult);
                return result;
            }
            throw new InvalidOperationException(LanguageResource.PipeEndInvokeBeforeBeginInvoke);
        }

        private T Execute(T arg)
        {
            return _funcStore.Aggregate(arg, (current, func) => func(current));
        }
    }
}